//
//  ST_DTChatFeed.swift
//  DrinkTogether
//
//  Created by DouLei on 2018/6/27.
//  Copyright © 2018 DouLei. All rights reserved.
//

import UIKit
import NIMSDK
import SwiftyJSON
import RealmSwift
import UserNotifications
import SwiftyUserDefaults
import RxSwift

/**
 小助手(old version)
 */
let SMART_ASSISTANT_SESSION_ID = "7febe044bdec97bfe6ba912f6ce4ed26"

/**
 官方客服MM (对话式)
 */
let DIALOGUE_ASSISTANT_SESSION_ID = "ea3b0f05723a0a9551016c4b40c1b7b7"

/**
 客服助手合集  新 老
 */
let ASSISTANT_SET = [SMART_ASSISTANT_SESSION_ID,DIALOGUE_ASSISTANT_SESSION_ID]

/**
 特质助手
 */
let PECULIARITY_ASSISTANT_SESSION_ID = "eb500840a15c7fc7d0da68d8eb5ab883"


/**
 伴心关注
 */
let FOLLOW_ASSISTANT_SESSION_ID = "7ea5f09500c7f2a7f51176420fab2b7b"



/**
 伴心喜欢助手
 */
let LOVE_ASSISTANT_SESSION_ID = "1bb11930044e5acbe773db6fe81ba137"

/**
 伴心评论
 */
let COMMENT_ASSISTANT_SESSION_ID = "5badba023f87033f784bf44647d66b9c"

//不展示的 session ,作为服务器和客户端通讯的通道
let SYSTEM_SESSION_ID = "4d2785e9fe6c7a40ece41ee2efdf396e"

//匹配通讯相关
let Match_SESSION_ID = "0aa071790b9e03da9507985d3b3b97d2"

//语音视频 通话 邀请
let INVITE_SESSION_ID = "fa1f51afdf4a6acf71ad14cccdfac293"

/// 最近通话不展示
let HIDDEN_RECENT_SESSION_SET:Set<String> = [SYSTEM_SESSION_ID,Match_SESSION_ID,INVITE_SESSION_ID]

let SYSTEM_SESSION_SET:Set<String> = [INVITE_SESSION_ID,
                                      Match_SESSION_ID,
                                      SYSTEM_SESSION_ID,
                                      COMMENT_ASSISTANT_SESSION_ID,
                                      FOLLOW_ASSISTANT_SESSION_ID,
                                      PECULIARITY_ASSISTANT_SESSION_ID,
                                      SMART_ASSISTANT_SESSION_ID,DIALOGUE_ASSISTANT_SESSION_ID,
                                      LOVE_ASSISTANT_SESSION_ID]

let UNREAD_SYSTEM_SESSION_SET:Set<String> = [COMMENT_ASSISTANT_SESSION_ID,FOLLOW_ASSISTANT_SESSION_ID,PECULIARITY_ASSISTANT_SESSION_ID,SMART_ASSISTANT_SESSION_ID,DIALOGUE_ASSISTANT_SESSION_ID]



class ST_DTChatFeed: NSObject {

    static let shared = ST_DTChatFeed()
    
    //    草稿 [userid:text]
    var draft = [String:String]()
    
    
    weak var chatAloneVC:ST_PrivateChatViewController?
    
    private override init() {
        super.init()
        
        NIMSDK.shared().chatManager.add(self)
        NIMSDK.shared().systemNotificationManager.add(self)
    }
    
    
    
    func systemMessage(message:NIMMessage){
        
        guard let session = message.session,session.sessionId == SYSTEM_SESSION_ID else { return  }
        
        var itemReceived:JSON?
        
        if let ext = message.remoteExt{
            itemReceived = JSON(ext)
        }else if let str = message.text{
            itemReceived = JSON(parseJSON: str)
        }
        
//        guard let remoteExt = message.remoteExt else{return}
//
//        let json = JSON.init(remoteExt)
        
        print("收到重要推送:",itemReceived ?? "无内容")
        
        guard let json = itemReceived else{return}
        
        if json["type"].stringValue == "super_hot" && json["data"]["effective"].boolValue == false{
            
            guard let account = ST_BTUserInfoManager.shared.current_account_info else{return}
            
            let realm = try! Realm()
            
            try! realm.write {
                account.extra_data?.super_hot = false
            }
            
            
            
        }
        /* 改为 系统通知类消息
        else if json["type"].stringValue == "like"{
            
            let dataJSON = json["data"]
            
            let model = ST_UpperHintModel.init(type: 0, accid: dataJSON["accid"].stringValue, avatar: dataJSON["avatar"].stringValue.compress_small_image(), nickName: dataJSON["nickname"].stringValue)
            
            main_thread_execute {
                ST_UpperHintManager.shared.toast(model: model)
                
                NotificationCenter.default.post(name: Notification.Name.received_love, object: nil)
                
            }
        }*/
            
            /// 弃用 超级喜欢
//        else if json["type"].stringValue == "super_like"{
//        }

//          取消匹配
        else if json["type"].stringValue == "remove_match"{
            
            let accid = json["data"]["target_accid"].stringValue
            
            ST_ConversationAdapter.shared.delete_recent_conversation(sessionId: accid)
                                    
            ST_BTUserInfoManager.shared.refresh_my_sweetheart_list()
            
        }
//      收到可滑动次数
        else if json["type"].stringValue == "slide_times"{
            
            let times = json["data"]["times"].intValue
            
            let video_status = json["data"]["video_status"].intValue
            
            guard let account = ST_BTUserInfoManager.shared.current_account_info else{return}
            
            let realm = try! Realm()
            
            try! realm.write {
                account.extra_data?.slide_times = times
                account.extra_data?.video_status = video_status
            }
            
            NotificationCenter.default.post(name: NSNotification.Name.my_user_info_updated, object: nil)
            
        }
//            用户信息更新
        else if json["type"].stringValue == "update_user"{
            
//            let data = json["data"]
            
//            let avatar = data["avatar"].stringValue
            
        }
        //    头像审核状态更新
        else if json["type"].stringValue == "face_avatar_approve"{
            main_thread_execute {
                FACE_AVATAE_STATE = json["data"]["face_avatar_state"].intValue
                NotificationCenter.default.post(name: Notification.Name.approved_avatar, object: nil)
                
                
                if FACE_AVATAE_STATE == 3{
                    
                    main_thread_execute(afterDelay: 1) {
                        GlobalPresent(toController: ST_MatchFaceSuccessController())
                    }
                }
                
            }
        }
        else if json["type"].stringValue == "withdraw_approve"{
            
            main_thread_execute {

                NotificationCenter.default.post(name: Notification.Name.sort_my_peculiarity, object: nil)
            }
        }
//        特质和相册 审核相关
        else if json["type"].stringValue == "feature_approve"{
            
            if json["data"]["type"].intValue == 1{
                main_thread_execute {
                    ST_PinterestHomeGuidanceManager.shared.unlock_look_active_person()
                }
            }
            
            NotificationCenter.default.post(name: Notification.Name.approved_peculiarity, object: nil, userInfo: ["status":json["data"]["type"].intValue])
        }else if json["type"].stringValue == "nickname_approve"{
            
            main_thread_execute {
                
                NotificationCenter.default.post(name: Notification.Name.nick_name_audit_failure, object: nil)
                
            }
        }
//        收到守护 刷新
        else if json["type"].stringValue == "guard_send"{
            
            main_thread_execute {
                
                ST_ConversationAdapter.shared.modify_my_guard(sentId: json["data"]["accid"].stringValue)
                //
                ST_BTUserInfoManager.shared.refresh_my_sweetheart_list()
                
                NotificationCenter.default.post(name: Notification.Name.receiveGuard, object: nil)
                
            }
        }
//        送会员 刷新
      else if json["type"].stringValue == "vip_send"{
          
          main_thread_execute {
              
            ST_BTUserInfoManager.shared.modify_member_expire(value: json["data"]["vip_expire"].intValue)
            
          }
      }else if json["type"].stringValue == "start_recommend"{
            
            
            main_thread_execute(afterDelay: 5) {
                
                    ST_BTLaunchController.shared.receive_copid_handle(json:json["data"])
            }
      }else if json["type"].stringValue == "yellow"{
        
            print("【鉴黄】不合规的 消息：",json)
        
            update_local_ext(ext: ["passedCheck" : false], session: NIMSession(json["data"]["target_accid"].stringValue, type: .P2P), msgId: json["data"]["bt_id"].stringValue)
        
      }
      // 视频语音涉嫌违规
      else if ["voice_forbid","video_forbid"].contains(json["type"].stringValue)  {
        
        print("【鉴黄】视频流 ，音频流 不合规的：",json)
        
        let jsonData = json["data"]
        
        NotificationCenter.default.post(name: NSNotification.Name.engagement_forbidden, object: nil, userInfo: ["channel":jsonData["channel"].stringValue,"title":jsonData["title"].stringValue,"content":jsonData["msg"].stringValue])
        
      }else if json["type"].stringValue == "award_push"{
          
          print("Alert Queue input json：",json)
          
          SCComponets.alert_dispatcher?.receive_award_task(array: json["data"].arrayValue)
          
      }else if json["type"].stringValue == "year_award_push"{
          
          print("【新年快乐】Alert Queue input json：",json)
          
          SCComponets.alert_dispatcher?.receive_happy_new_year_award(itemJson: json["data"])
          
      }
        
        
        

//        收到 匹配 成功
        
        
        
//        系统消息变为已读
        NIMSDK.shared().conversationManager.markAllMessagesRead(in: session)
        
        
        ST_BTLaunchController.shared.setting_unread_msg_count()
        
        print("系统消息标记为已读 ID = ：",session.sessionId)
    }
    
    
    
    
}


//MARK: - 更新本地NIMMessage LocalExt
extension ST_DTChatFeed{
    
    func update_local_ext(ext:[String:Any],session:NIMSession,msgId:String){
        
        
        guard let msgList = NIMSDK.shared().conversationManager.messages(in: session, messageIds: [msgId]),let msg = msgList.first else{
            
            if ext.keys.contains("passedCheck"){
                print("【鉴黄】update_local_ext 没有这个消息")
            }else{
                print("Bug--9--","没有这个消息")
            }
            
            
            return
        }
        
        msg.localExt = ext
        
        NIMSDK.shared().conversationManager.update(msg, for: session) { (error) in
            
            if let e = error{
                
                
                if ext.keys.contains("passedCheck"){
                    print("【鉴黄】update_local_ext 更新本地消息错误---",e)
                }else{
                    print("Bug--9--","更新本地消息错误---",e)
                }
                
            }else{
                print("Bug--9--","更新本地消息成功")
                
                
                if ext.keys.contains("passedCheck"){
                    print("【鉴黄】update_local_ext 更新本地消息成功 uuid =",msgId)
                }else{
                    print("Bug--9--","更新本地消息成功")
                }
                
                let info = ["msgIdSet":msgId,"ext":ext] as [String : Any]
                
                NotificationCenter.default.post(name: Notification.Name.i_m_message_local_ext_updated, object: nil, userInfo: info)
            }
        }
    }
    
}

extension ST_DTChatFeed{
    
    func sendSimulateWechatNumberMessage(sessionId:String,anotherWechat:String) {
        
        
        let message = NIMMessage()
        
        let attach = ST_Custom2649AttachmentModel()
        
        attach.wechatText = "哇偶~我们已经这么亲密了呀！看来你就是我要寻找的那个人！嘻嘻！现在我们可以\(Defaults[.PandaWriteKindStr])畅聊啦！并且我的微信号也是你的了，请一定要收好哦：" + anotherWechat
        
        let customObj = NIMCustomObject()
        
        customObj.attachment = attach
        
        message.messageObject = customObj
        
        NIMSDK.shared().conversationManager.save(message, for: NIMSession.init(sessionId, type: NIMSessionType.P2P)) { (error) in

            print("插入消息错误 ---:",error ?? "-无--")
            
        }
        
    }
    
}

//MARK: - Nim  delegate
extension ST_DTChatFeed:NIMSystemNotificationManagerDelegate{
    
    func onReceive(_ notification: NIMCustomSystemNotification) {
        
        print("收到自定义系统通知1：",notification)
        
        guard let content = notification.content else{return}
        
        let json = JSON.init(parseJSON: content)
        
        
        /*
        if json["type"].stringValue == "like"{
            
            let dataJSON = json["data"]
            
            let model = ST_UpperHintModel.init(type: 0, accid: dataJSON["accid"].stringValue, avatar: dataJSON["avatar"].stringValue.compress_small_image(), nickName: dataJSON["nickname"].stringValue)
            
            main_thread_execute {
                
                ST_UpperHintManager.shared.toast(model: model)
                
                NotificationCenter.default.post(name: Notification.Name.received_love, object: nil)
                
            }
            
        }*/
        
        if json["type"].stringValue == "member_match"{
            
            let dataJSON = json["data"]
            
            let model = ST_UpperHintModel.init(type: 1, accid: dataJSON["accid"].stringValue, avatar: dataJSON["avatar"].stringValue, nickName: dataJSON["nickname"].stringValue)
            
            main_thread_execute {
                
                ST_BTUserInfoManager.shared.receive_match(json: dataJSON)
                
                ST_UpperHintManager.shared.toast(model: model)
                
                ST_ChatModuleViewController.shared.receive_match_handle(accid: dataJSON["accid"].stringValue)
                
                
            }
        }
        
           
    }
    
    func onReceive(_ notification: NIMSystemNotification) {
        print("收到自定义系统通知2：",notification)
    }
 
}
extension ST_DTChatFeed:NIMChatManagerDelegate{
    
    func onRecvRevokeMessageNotification(_ notification: NIMRevokeMessageNotification) {
        
        guard let  msg = notification.message else{return}
        
        
        main_thread_execute {
                        
            if let vc = self.chatAloneVC {
                
                if vc.sessionID == msg.session?.sessionId{
                    
                    vc.recallMessage(messageId: msg.messageId,isMyOperation: false)
                }
            }
            
            ST_ConversationAdapter.shared.refresh_all_data()
            
        }
    }
    
    func onRecvMessages(_ messages: [NIMMessage]) {
     
        
//        时间要大于启动时间
        let inviteMsgs = messages.filter({$0.session?.sessionId == INVITE_SESSION_ID && $0.timestamp > ST_DTBootManager.shared.bootDate.unixTimestamp })
        
        if inviteMsgs.count > 0{
            
            ST_MediaChatDispatcher.shared.recive_invite_system_message(messages: inviteMsgs)
        }
        
//        print("消息来啦")
        
        var sessionIds = Set<String>()
        
        for message in messages {

            guard let session = message.session,session.sessionId != INVITE_SESSION_ID,message.isOutgoingMsg == false else { continue }
            
//            喜欢红点
            if session.sessionId == LOVE_ASSISTANT_SESSION_ID{
                
                NotificationCenter.default.post(Notification.init(name: Notification.Name.refresh_love_me))
                
            }
            
            //            系统通知类消息
            if session.sessionId == SYSTEM_SESSION_ID{
                main_thread_execute {
                    self.systemMessage(message: message)
                }
                continue
            }
            
            //     重要匹配类消息 能执行代码的情况 全部设置为已读
            if session.sessionId == Match_SESSION_ID{
 
                main_thread_execute {
                    self.systemMessage(message: message)
                }
                continue
            }
            
            sessionIds.update(with: session.sessionId)
            
            guard let model = ST_DTChatMessage.analysis(message: message) else{
                continue
            }
            
            
//            收到守护 增加\(Defaults[.PandaStr])
            if model.cellStyle == .incomeGuard{
                
                if let str = model.customAttachment255?.subTitle,let income = self.find_income_from(str: str){
                    
                    ST_BTUserInfoManager.shared.increase_income(value: income, msgSendDate: Date(timeIntervalSince1970: TimeInterval(model.messageTime)))
                    
                }
                
////                守护我 更新头像 置顶等
//                if model.cellStyle == .incomeGuard{
//
//                    ST_ConversationAdapter.shared.modify_my_guard(sentId: model.chatID)
//
//                    ST_BTUserInfoManager.shared.refresh_my_sweetheart_list()
//
//                }
//
            }
            
            
            if model.cellStyle == .incomeGift || model.cellStyle == .incomeGuard{
                
                NotificationCenter.default.post(name: Notification.Name.received_income_gift, object: nil, userInfo: ["msg":model])
            }
            
            let isNotFirst = ST_ConversationAdapter.shared.sessionList.contains(where: ({$0.sessionId == model.chatID}))
            
            ST_BTGlobalDataCenter.shared.receive_chat_message_event(sessionId: model.chatID, isFirst: isNotFirst, isFirstReceive: false)
            
            main_thread_execute {
                
                if let vc = self.chatAloneVC {
                    
                    if vc.sessionID == model.chatID{
                        //                    vc.insertModel(model)
                        vc.append_model(model, receive: true)
                    }
//                    vc.settingUnreadCount()
                }
            }
        }
        
        
        
        main_thread_execute {
            
            ST_ConversationAdapter.shared.refresh_all_data()
        }
        
        
    }
    
    
}

//MARK: - public Method
extension ST_DTChatFeed{
    
    
    func find_income_from(str:String)->Double?{
        
        var numberStr = ""
        for item in str {
//            是数字
            if let v = item.string.int,Array(0...9).contains(v){
                numberStr += v.string
            }
            if item == "."{
                numberStr += "."
            }
        }
        
        return numberStr.double()
    }
    
    /**
     发送通话记录📝
     paramters:
     agoraType 1语音， 2视频
     */
    func sendCallRecord(sessionId:String,agoraType:Int,recordtype:ST_TIANRecordType,time:Float = 0) {
        
        
        let msg = NIMMessage()
        
        let tianModel = ST_Tian270AttachmentModel()
        
        tianModel.agoraType = agoraType
      
        tianModel.type = recordtype
            
        tianModel.time = time
        
        let customObj = NIMCustomObject()
        
        customObj.attachment = tianModel
        
        msg.messageObject = customObj
        
        try? NIMSDK.shared().chatManager.send(msg, to: NIMSession.init(sessionId, type: NIMSessionType.P2P))
        
        ST_ConversationAdapter.shared.refresh_all_data()
        
        let model = ST_DTChatMessage.analysis(message: msg)
        
        if let vc = self.chatAloneVC ,let m = model{
            
            if vc.sessionID == sessionId{
                
                vc.append_model(m)
            }
        }
        
        
    }
}


